package com.hansheng.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by GoldenMan on 17/5/10.
 */
@Aspect
public class LogManager {
    private final static Log log = LogFactory.getLog(LogManager.class);
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        Class clazz = pjp.getTarget().getClass();
        StringBuffer logMsg = new StringBuffer();// 日志信息
        logMsg.append("\n开始执行 ").append(clazz).append(" 类的 ").append(pjp.getSignature().getName()).append(" 方法");
        log.info(logMsg);
        System.out.println(logMsg);
        String cl = clazz.getName().substring(clazz.getName().lastIndexOf(".") + 1);
        String method = pjp.getSignature().getName();
        System.out.println("============" + cl + "&" + method + "============");
        log.info("============" + cl + "&" + method + "============");
        Object retVal = pjp.proceed();
        System.out.println("============方法执行结束！============");
        log.info("方法执行结束\n");
        return retVal;
    }

    /**
     * @param detailErrMsg 详细错误信息
     * @Description: 日志异常
     * @author： GoldenMan
     * @createTime： 2017-5-14
     */
    public void writeLog(String detailErrMsg, JoinPoint joinPoint, Exception ex) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.
                getRequestAttributes()).getRequest();
        //获取请求的URL
        StringBuffer requestURL = request.getRequestURL();
        //获取参 数信息
        String queryString = request.getQueryString();
        //封装完整请求URL带参数
        if (queryString != null) {
            requestURL.append("?").append(queryString);
        }

        String cla = joinPoint.getTarget().getClass().getName();//action
        String method = joinPoint.getSignature().getName();//method
        try {

            //创建输出异常log日志
            File file = new File("d:/test/" + System.currentTimeMillis() + method + ".log");
            //if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream out = new FileOutputStream(file, true); //如果追加方式用true
            //日志具体参数
            StringBuffer sb = new StringBuffer();
            sb.append("-----------" + df.format(new Date()) + "------------\r\n");
            sb.append("远程请求URL[" + requestURL + "]\r\n");
            sb.append("接口方法：[" + cla + "." + method + "]\r\n");
            sb.append("详细错误信息：" + ex + "\r\n");
            sb.append(detailErrMsg + "\r\n");
            out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
            out.close();

            System.out.println("Done");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
